package com.jiayou.config.vertx.handler.httpstate

import io.vertx.core.json.JsonObject
import io.vertx.core.json.impl.JsonUtil
import io.vertx.ext.web.Router
import io.vertx.ext.web.handler.HttpException

/**
@author lishuang
@data   2021-06-25  16:06:44
@info   异常处理handler
 */
class HttpStateHandler {
    companion object {
        val STATUS = arrayOf(400, 401, 402, 403, 405, 500)
        fun errorHandle(status: Array<Int>, router: Router) {
            status.forEach { statusItem ->
                router.errorHandler(statusItem) { routerContext ->
                    routerContext.response().statusCode = routerContext.statusCode()
                    routerContext.response().putHeader("Content-Type", "application/json")
                    val errorInfo = JsonObject().put("code", routerContext.statusCode()).put("data", null)
                    when (routerContext.statusCode()) {
                        400 -> errorInfo.put("message", "客户端请求错误！")
                        401 -> errorInfo.put("message", "拒绝访问，请携带你的身份信息！")
                        403 -> errorInfo.put("message", "无该资源的访问权限！")
                        405 -> errorInfo.put("message", "访问不被支持的资源！")
                        500 -> {
                            errorInfo.put("message", "服务器内部错误：" + routerContext.failure().message)
                            routerContext.failure().printStackTrace()
                        }
                    }
                    routerContext.response().end(errorInfo.encode())
                }
            }
        }
    }
}
